package org.jeecg.modules.water.service.impl;




import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jeecg.modules.water.entity.LoraResponse;
import org.jeecg.modules.water.entity.LwgyJointWater;
import org.jeecg.modules.water.entity.LwgyJointWaterCmd;
import org.jeecg.modules.water.entity.LwgyJointWaterConfiguration;
import org.jeecg.modules.water.mapper.LwgyJointWaterConfigurationMapper;
import org.jeecg.modules.water.mapper.LwgyJointWaterMapper;
import org.jeecg.modules.water.service.ILwgyRelaxLoraConnectionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


//轻松表计对接（lora）
@Service
public class LwgyRelaxLoraConnectionServiceImpl extends ServiceImpl<LwgyJointWaterMapper, LwgyJointWater> implements ILwgyRelaxLoraConnectionService {
    @Resource
    private LwgyJointWaterConfigurationMapper lwgyJointWaterConfigurationMapper;

    public static String STATIONCODE = "538478";//鲁维电子oem项目群 莫忘初心 吕工提供
    public static String JOINFLAG = "QING_SONG";
    public static String QINGSONGHEAD = "http://nb.sdqsbj.com";
    public static String CHECK_DEVICEINFO_URL = "/api/third/open/thirdFactory/v1/checkDeviceInfo";//鲁维电子oem项目群 柚子 高工提供文档及ip
    public static String SEND_CMD_URL = "/api/third/open/thirdFactory/v1/sendCmd";//开关阀
    public static String GET_MESSAGE_URL = "/api/third/open/thirdFactory/v1/getMessages";//手动获取抄表信息
    public static String DEVICECODE = "00005386";//采集器010020180017 设备編码 00005386
    public static String USERCODE = "00005386";//第三方用户编码


    //表具校验 //：第三方系统调用轻松系统接口，向轻松系统发送一组表号，如该表号存在并在该分站下则返回表具通讯码等信息，如不存在则不返回任何信息。
    public String checkdeviceinfo(LwgyJointWaterConfiguration lwgyJointWaterConfiguration) {
        //时间戳
        //密钥 请求秘钥，由当前时间戳+轻松系统分配的jo inFlag拼接进行MD5，32位小写加密。
     /*   long timestamp = System.currentTimeMillis();
        String secret=timestamp+JOINFLAG;*/


        try {
            String url = QINGSONGHEAD + CHECK_DEVICEINFO_URL;
            System.out.println("url=========:" + url);
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            // 设置请求方法为 POST
            con.setRequestMethod("POST");
            // 设置请求头信息
            con.setRequestProperty("Content-Type", "application/json");

            // 构建请求体数据
            RequestData requestData = new RequestData();
            requestData.getMeterCodes().add("");
            requestData.getUserCodes().add(lwgyJointWaterConfiguration.getDeviceNumber());
            requestData.setKey("string");

            // 使用Gson库将对象转换为JSON字符串
            Gson gson = new Gson();
            String jsonData = gson.toJson(requestData);

            // 发送POST请求
            con.setDoOutput(true);
            try (OutputStream os = con.getOutputStream()) {
                byte[] input = jsonData.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 获取响应结果
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 解析JSON数据
            LoraResponse apiResponse = gson.fromJson(response.toString(), LoraResponse.class);

            // 输出解析结果
            System.out.println("response.toString(),: " + response.toString());
            System.out.println("Code: " + apiResponse.getCode());
            System.out.println("Message: " + apiResponse.getMsg());
            // 可以根据需要输出其他字段的信息
            //{"code":0,"msg":"处理成功",
            // "data":[{"id":null,"type":null,"imei":"869691072622562","sim":"898604C91122D0082165","devicetype":null,"deviceid":null,"devicecode":null,"frame":null,"isp":"1","ispid":"2137570547","stationcode":null,"state":null,"createtime":null,"sendtime":null,"finishtime":null,"basenum":null,"newdevicecode":null,"readperiod":"48","outerid":null,"valve":null,"valvestate":"OPEN","curnum":"0.13","signalstrength":"30","sensor":"0","centerCode":null,"childCode":null,"controlmetercode":null,"node":null,"model":null,"readtime":null,"hour":null,"day":null,"voltage":null,"channel":null,"updatetime":null,"times":null,"voltagealarm":null,"magneticalarm":null,"ip":null,"port":null,"resultframe":null,"counter":null,"battery":"0","code":"260324051003"}]}

            return response.toString();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("调用轻松表计鉴权接口报错");
            return null;
        }
    }


    //开关阀控制
  /* public String sendCmd(LwgyJointWaterCmd lwgyJointWaterCmd){

       try{
           long timestamp = new Date().getTime();
            String secret = getMD5(timestamp + JOINFLAG);


           JSONObject requestData = new JSONObject();
           requestData.put("ispid", lwgyJointWaterCmd.getIspid());
           requestData.put("stationcode", STATIONCODE);
           requestData.put("outerid", lwgyJointWaterCmd.getId());
           requestData.put("type", lwgyJointWaterCmd.getType());
           JSONArray jsonArray = new JSONArray();
           jsonArray.add(requestData);

           CloseableHttpClient httpClient = HttpClients.createDefault();
           HttpPost httpPost = new HttpPost(QINGSONGHEAD+SEND_CMD_URL);
           httpPost.addHeader("Content-Type", "application/json");
           httpPost.addHeader("times", String.valueOf(timestamp));
           httpPost.addHeader("stationcode", STATIONCODE);
           httpPost.addHeader("secret",secret);

           StringEntity entity = new StringEntity(jsonArray.toString());
           httpPost.setEntity(entity);
           HttpResponse response = httpClient.execute(httpPost);
           System.out.println("httpPost"+httpPost);
           System.out.println("========"+QINGSONGHEAD+SEND_CMD_URL);
           System.out.println("========"+jsonArray);
           String result = EntityUtils.toString(response.getEntity());
           httpClient.close();
           return result;
       }catch (Exception e){
           e.printStackTrace();
           System.out.println("调用轻松表计鉴权接口报错");
           return null;
       }


    }

    //手动获取抄表信息
    public String getMessages(String ispid,String begintime,String endtime){
        try{
            long timestamp = new Date().getTime();
            String secret = getMD5(timestamp + JOINFLAG);


         *//*   JSONObject requestData = new JSONObject();
            requestData.put("ispid",ispid);
            requestData.put("begintime", begintime);
            requestData.put("endtime", endtime);

            JSONArray jsonArray = new JSONArray();
            jsonArray.add(requestData);*//*

            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(QINGSONGHEAD+GET_MESSAGE_URL);
            httpPost.addHeader("Content-Type", "application/json");
            httpPost.addHeader("times", String.valueOf(timestamp));
            httpPost.addHeader("stationcode", STATIONCODE);
            httpPost.addHeader("secret",secret);
            String json = "{\"ispid\":\"" + ispid + "\",\"begintime\":\"" + begintime + "\",\"endtime\":\"" + endtime + "\"}";
            StringEntity entity = new StringEntity(json,"UTF-8");
            httpPost.setEntity(entity);
            System.out.println("========================="+httpPost);

            HttpResponse response = httpClient.execute(httpPost);
            String result = EntityUtils.toString(response.getEntity());
            System.out.println("========================="+result);
            httpClient.close();
            return result;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("调用轻松表计鉴权接口报错");
            return null;
        }
    }



    public static String getMD5(String input) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(input.getBytes());
        StringBuilder sb = new StringBuilder();
        for (byte b : messageDigest) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }*/
// 定义数据对象结构
    public static class RequestData {
        private List<String> meterCodes = new ArrayList<>();
        private List<String> userCodes = new ArrayList<>();
        private String key;

        public List<String> getMeterCodes() {
            return meterCodes;
        }

        public List<String> getUserCodes() {
            return userCodes;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getKey() {
            return key;
        }
    }
}
